using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Text.RegularExpressions;

namespace findExtrinsic
{
    class CoordinateTextBox : TextBox
    {
        public event EventHandler IsNowValid;
        public event EventHandler NoLongerValid;

        private bool validCoord;
        private double x; public double X { get { return x; } }
        private double y; public double Y { get { return y; } }
        private double z; public double Z { get { return z; } }

        private Point _imagePoint;

        public Point ImagePoint
        {
            get { return _imagePoint; }
            set { _imagePoint = value; }
        }

        Font boldFont, regFont;

        public bool IsValid
        {
            get { return validCoord; }
        }

        public CoordinateTextBox()
        {
            this._imagePoint.X = -5;
            this._imagePoint.Y = -5;

            this.Width = 96;
            this.Margin = new Padding(3, 1, 3, 1);
            this.LostFocus += new EventHandler(CoordinateTextBox_LostFocus);
            this.TextChanged += new EventHandler(CoordinateTextBox_TextChanged);
            boldFont = new Font(this.Font, FontStyle.Bold);
            regFont = new Font(this.Font, FontStyle.Regular);
        }

        void CoordinateTextBox_LostFocus(object sender, EventArgs e)
        {
            this.BackColor = Color.White;
        }

        void CoordinateTextBox_TextChanged(object sender, EventArgs e)
        {
            double newX, newY, newZ;
            bool newValid = false;

            string[] coords = this.Text.Split(',');
            if(coords.Length == 3)
                for (int i = 0; i < 3; i++)
                {
                    try { newX = Convert.ToDouble(coords[0]);  }
                    catch { newValid = false; break; }

                    try { newY = Convert.ToDouble(coords[1]);  }
                    catch { newValid = false; break; }

                    try { newZ = Convert.ToDouble(coords[2]); }
                    catch { newValid = false; break; }

                    x = newX; y = newY; z = newZ;
                    newValid = true;
                }

            if (newValid)
                this.Font = boldFont;
            else
                this.Font = regFont;

            if (newValid != validCoord)
            {
                if (newValid && IsNowValid != null) IsNowValid(this, null);
                if (!newValid && NoLongerValid != null) NoLongerValid(this, null);
                validCoord = newValid;
            }

        }

    }
}
